package com.chookss.home.tuwen;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.home.entity.TuwenEntity;
import com.chookss.mine.entity.MyViedeoEntity;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.RecycleViewDivider;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.lvgroup.hospital.base.BaseAct;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;
import scut.carson_ho.searchview.EditText_Clear;

public class MyTuwenActivity extends BaseAct {


    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.rvView)
    RecyclerView recyclerView;
    @BindView(R.id.srlView)
    SmartRefreshLayout smrRf;
    @BindView(R.id.ivNone)
    ImageView ivNone;
    @BindView(R.id.tvNone)
    TextView tvNone;
    @BindView(R.id.tvNone2)
    TextView tvNone2;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.llBg)
    LinearLayout llBg;
    private TuwenAdapter tuwenAdapter;
    private List<TuwenEntity> listData = new ArrayList<>();
    private int currentPage = 1;
    private boolean isEnd = false;//是否到底
    private String keyWords = "";
    private int index = -1;//默认不选择

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(R.layout.common_srlview_center);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        commonTitleTxt.setText("我的图文");
        NavigationTools.saveUseRecord(this, "1", "17");
        smrRf.setPadding(0, Utils.dip2px(this, 12), 0, 0);
        llBg.setBackgroundColor(getResources().getColor(R.color.white));
        recyclerView.setPadding(Utils.dip2px(this,12),0,Utils.dip2px(this,12),0);
        ivNone.setBackgroundResource(R.drawable.icon_default_no_common);
        tvNone.setText("图文还是空的");
        tvNone2.setText("快去发布你的第一条图文吧");
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, Utils.dip2px(this, 0.5f), getResources().getColor(R.color.line_gray)
        ));
        tuwenAdapter = new TuwenAdapter(R.layout.item_tuwen, this, listData, 1);
        recyclerView.setAdapter(tuwenAdapter);
        smrRf.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        smrRf.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                currentPage = 1;
                isEnd = false;
                getData();
            }
        });
        smrRf.autoRefresh();
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", "20");
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<TuwenEntity>>>() {
        }.getType(), null, Urls.getTuwengetMyList, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<TuwenEntity>>() {
            @Override
            public void onSuccess(List<TuwenEntity> data) {
                loadEnd();
                if (currentPage == 1) {
                    listData.clear();
                    tuwenAdapter.notifyDataSetChanged();
                }
                if (smrRf == null || llNone == null) {
                    return;
                }
                int oldIndex=listData.size();
                if (data != null && data.size() > 0) {
                    listData.addAll(data);
                    tuwenAdapter.notifyItemRangeChanged(oldIndex,data.size());
                    smrRf.setVisibility(View.VISIBLE);
                    llNone.setVisibility(View.GONE);
                } else {
                    isEnd = true;
                    if (listData.size() == 0) {
                        smrRf.setVisibility(View.GONE);
                        llNone.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }
    private void loadEnd() {
        if (null != smrRf && smrRf.getState() == RefreshState.Refreshing)
            smrRf.finishRefresh(true);
        if (null != smrRf && smrRf.getState() == RefreshState.Loading)
            smrRf.finishLoadMore(true);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();
             if (map.containsKey("deleteTuwenId")) {
                deleteTuwen(map.get("deleteTuwenId"));
            }
        }
    }
    private void deleteTuwen(String id) {
        if(smrRf==null||llNone==null){
            return;
        }
        for (int i = 0; i < listData.size(); i++) {
            TuwenEntity tuwenEntity = listData.get(i);
            if (tuwenEntity.getId().equals(id)) {
                listData.remove(i);
                tuwenAdapter.notifyItemRemoved(i);
                tuwenAdapter.notifyItemRangeChanged(i, listData.size() - i);
                if (listData.size() == 0) {
                    smrRf.setVisibility(View.GONE);
                    llNone.setVisibility(View.VISIBLE);
                }
            }
        }
    }
    @OnClick({R.id.common_title_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
        }
    }
}
